package org.example.steamshop.service;

import org.example.steamshop.form.GameForm;
import org.example.steamshop.model.Game;
import org.example.steamshop.repository.GameRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class GameService {
    @Autowired
    private GameRepository gameRepository;

    public Game findGameById(Long id) {
        return gameRepository.findById(id).orElse(null);
    }
    public Page<Game> findGamesByName(String keyword, Pageable pageable) {
        return gameRepository.findByNameLikeAndStatus("%" + keyword + "%", "在售中", pageable);
    }



    // 分页查询所有在售中的游戏

    public Page<Game> findOnSaleGames(Pageable pageable) {
        return gameRepository.findByStatus("在售中", pageable);
    }

    public List<Game> findOnSaleGames() {
        return gameRepository.findByStatus("在售中");
    }

    // 新增方法：获取所有状态的游戏（用于管理后台）
    public List<Game> findAllGames() {
        return gameRepository.findAll(); // 使用JPA自带的findAll()
    }

    // 按类别查询在售中的游戏
    public Page<Game> findGamesByCategory(String category, Pageable pageable) {
        return gameRepository.findByCategoryAndStatus(
                category, "在售中", pageable);
    }

    /**
     * 更新游戏状态
     */
    public Game updateGameStatus(Long id, String status) {
        return gameRepository.findById(id)
                .map(game -> {
                    game.setStatus(status);
                    return gameRepository.save(game);
                })
                .orElseThrow(() -> new IllegalArgumentException("游戏ID不存在：" + id));
    }

    // 根据状态查询游戏
    public List<Game> findGamesByStatus(String status) {
        return gameRepository.findByStatus(status);
    }


    public boolean existsByName(String name) {
        return gameRepository.existsByName(name);
    }


    // 新增：添加游戏的方法
    @Transactional
    public Game addGame(Game game) {

        if (game.getStatus() == null || game.getStatus().isEmpty()) {
            game.setStatus("在售中");
        }
        return gameRepository.save(game);
    }






}